package org.luo.common.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.luo.common.common.Result;
import org.luo.common.utils.JwtUtil;
import org.luo.common.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

@Component
@ConditionalOnClass({Result.class})
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if("OPTIONS".equals(request.getMethod())){
            return true;
        }
        Map<String, Object> claims = new HashMap<>();
        String idStr = request.getHeader("id");
        if( idStr != null && !idStr.isBlank()){
            Integer id = Integer.valueOf(request.getHeader("id")) ;
            claims.put("id", id);
        }

        String username = request.getHeader("username");
        claims.put("username", username);
        ThreadLocalUtil.set(claims);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        ThreadLocalUtil.remove();
    }
}
